/**
 * File:bc.ui
 * Youth is just a unoptimized code!
 * -------------------------------------------------------------------------
 * Created by BigQ on 2016/9/21.
 *--------------------------------------------------------------------------
 * This technical information is confidential information,
 * without my written permission is prohibited for commercial purposes.　
 *--------------------------------------------------------------------------
 */
;(function ($) {
    var bcSpinner = function (ele, options) {
        this.SpinnerWrap = this.element = $(ele);
        this.defaults = {
            version: 'version 1.0.0',
            value: 0,
            min: 0,
            max: 9999999,
            step: 1,
            change:null
        };
        this.options = $.extend({}, this.defaults, options);
    };
    bcSpinner.prototype = {
        render: function () {
            this._init();
            return this;
        },
        _init: function () {
            var self = this, p = this.options;
            if (p.value > p.max || p.value < p.min) {
                p.value = p.min;
            }
            self.element.addClass("spinner_text");
            self.element.val(p.value).attr("readonly", "readonly").keypress(function () {
                return (/[\d]/.test(String.fromCharCode(event.keyCode)));
            }).bind("copy cut paste", function (e) {
                return false;
            });
            var decreaseBtn = $('<a  class="subtract" href="javascript:void(0)">-</a>').click(function () {
                self._changeValue(-1)
            });
            var increaseBtn = $('<a  class="subtract" href="javascript:void(0)">+</a>').click(function () {
                self._changeValue(1)
            });
            self.element.before(decreaseBtn).after(increaseBtn);
        },
        _changeValue: function (d) {
            var value = parseInt(this.element.val());
            if (isNaN(value)) {
                value = this.options.min;
            }
            var _val = value + d * this.options.step;

            if (_val <= this.options.max && _val >= this.options.min) {
                value = _val;
            }
            this.element.val(value);
            if(this.options.change && $.isFunction(this.options.change)){
                this.options.change(value);
            };
        }
    };
    $.fn.bcSpinner = function (options) {
        var bcSpinnerArr=[];
        $(this).each(function () {
            var bcSpinnerEle = new bcSpinner(this, options);
            bcSpinnerArr.push(bcSpinnerEle.render());
        });
        if(bcSpinnerArr.length == 1){
            return bcSpinnerArr[0];
        }
        else{
         return   bcSpinnerArr;
        }
    };
})(jQuery);